package com.iphanta.community.mq;

import com.baidu.fsg.uid.UidGenerator;
import com.iphanta.community.common.utils.JsonUtils;
import com.iphanta.community.common.utils.RedisKeyUtils;
import com.iphanta.community.mq.message.Notification;
import com.iphanta.community.user.entity.UserNotification;
import com.iphanta.community.user.mapper.UserNotificationMapper;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 墨声 E-mail: zehong.hongframe.huang@gmail.com
 * create time: 3/10/22 11:21 AM
 */
@Service
@RocketMQMessageListener(
        topic = "user-notifications",
        consumerGroup = "user-notifications-group",
        consumeThreadMax = 32
)
public class NotificationsListener implements RocketMQListener<Notification> {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserNotificationMapper notificationMapper;

    @Autowired
    private UidGenerator uidGenerator;

    @Override
    public void onMessage(Notification message) {
        String notificationKey = RedisKeyUtils.INSTANCE.key("notification", message.getType(), message.getUid());
        String isReadKey = RedisKeyUtils.INSTANCE.key("notification", "is_read", message.getType(), message.getUid());
        String data = JsonUtils.INSTANCE.toJsonString(message);
        this.redisTemplate.execute(new SessionCallback<Integer>() {
            @Override
            public Integer execute(RedisOperations operations) throws DataAccessException {
                operations.multi();
                operations.opsForValue().set(isReadKey, "0");
                operations.opsForList().leftPush(notificationKey, data);
                operations.expire(notificationKey, 24, TimeUnit.HOURS);
                List result = operations.exec();
                return result.size();
            }
        });

        UserNotification userNotification = new UserNotification();
        BeanUtils.copyProperties(message, userNotification);
        userNotification.setId(this.uidGenerator.getUID());
        this.notificationMapper.insert(userNotification);
    }
}
